package com.jv.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /**
     * 从下往上写比较方便：先写Realm，再写DefaultWebSecurityManager,再写ShiroFilterFactoryBean
     */
    //shiroFilterFactoryBean
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager desecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(desecurityManager);
        //添加Shiro的内置过滤器
        Map<String, String> filterMap = new LinkedHashMap<>();

        /**
         * anon: 无需认证就可以访问
         * authc: 必须认证才能访问
         * user: 拥有RememberMe 功能才能访问
         * perm: 拥有对某个资源的权限才能访问
         * role: 拥有某个角色权限才能访问
         */
        filterMap.put("/user/add","perm[user:add]");//如果没有"user:add"权限，则不能访问，在数据中其实是用“user:add”这个字符串来表示user的add权限。。
        filterMap.put("/user/update","authc");//认证成功才能访问
        factoryBean.setFilterChainDefinitionMap(filterMap);
        //设置登录的请求
        factoryBean.setLoginUrl("/toLogin");
        return factoryBean;
    }
    //DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //Realm
    @Bean(name = "userRealm")//默认对象名是方法名
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
